<script>
export default {
  name: 'RouteView',
  props: {
    keepAlive: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    cachedViews () {
      return this.$store.state
    }
  },
  data () {
    return {
    }
  },
  render () {
    const { $route: { meta }, $store: { getters } } = this
    const inKeep = (
      <keep-alive>
        <router-view if = { this.$route.meta.keepAlive } key={ this.$route.fullPath }/>
      </keep-alive>
    )
    const notKeep = (
      <router-view />
    )
    // 这里增加了 multiTab 的判断，当开启了 multiTab 时
    // 应当全部组件皆缓存，否则会导致切换页面后页面还原成原始状态
    // 若确实不需要，可改为 return meta.keepAlive ? inKeep : notKeep
    if (!getters.multiTab && !meta.keepAlive) {
      return notKeep
    }
    return this.keepAlive || getters.multiTab || meta.keepAlive ? inKeep : notKeep
  },
  mounted () {
    // 注册监听全局的clearKeepAlive方法,可在其他组件中触发此方法
    this.$bus.$on('clearKeepAlive', this.clearKeepAlive)
  },
  methods: {
    // 根据fullUrl清除keepAlive
    clearKeepAlive (fullUrl) {
      // console.log('bus触发要清除的keepAlive', fullUrl);
      var currentNode = this
      console.log('root-vnode', currentNode)
      if (currentNode.parent) {
        currentNode = currentNode.parent
      }
      currentNode.$children.forEach((item) => {
        // console.log('vnode', item.$vnode)
        if (item.$vnode.data.key === fullUrl || (item.$vnode.data.key && item.$vnode.data.key.indexOf(fullUrl) >= 0)) {
          this._myDestory(item)
        }
      })
    },
    // 封装清除某个组件的keepAlive状态,并销毁
    _myDestory (keepAliveComponent) {
      // 你可以根据自己的业务更改此处的判断逻辑，酌情决定是否摧毁本层缓存。
      if (keepAliveComponent.$vnode && keepAliveComponent.$vnode.data.keepAlive) {
        if (keepAliveComponent.$vnode.parent && keepAliveComponent.$vnode.parent.componentInstance && keepAliveComponent.$vnode.parent.componentInstance.cache) {
          if (keepAliveComponent.$vnode.componentOptions) {
            var key = keepAliveComponent.$vnode.key == null ? keepAliveComponent.$vnode.componentOptions.Ctor.cid +
              (keepAliveComponent.$vnode.componentOptions.tag ? `::${keepAliveComponent.$vnode.componentOptions.tag}` : '') : keepAliveComponent.$vnode.key
            var cache = keepAliveComponent.$vnode.parent.componentInstance.cache
            var keys = keepAliveComponent.$vnode.parent.componentInstance.keys
            if (cache[key]) {
              if (keys.length) {
                var index = keys.indexOf(key)
                if (index > -1) {
                  keys.splice(index, 1)
                }
              }
              delete cache[key]
            }
          }
        }
      }
      keepAliveComponent.$destroy()
    }
  }
}
</script>
